package com.tao.controller;

import com.tao.pojo.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    /* 实现fromData上传*/
    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            return ResponseResult.error("文件不存在！");
        }
        // 获得原文件名
        String filename = file.getOriginalFilename();
        // 通过符号截取符号之前数据
        String substring = filename.substring(0,filename.indexOf("."));
        // 通过符号截取符号之后数据
        String extension = filename.substring(filename.lastIndexOf("."));

        //创建一个目录对象
        File dir = new File("images");
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }
        long time = System.currentTimeMillis();
        StringBuilder fileName= new StringBuilder(substring+time+extension);
        // 将临时文件转存到指定位置
        try {
            file.transferTo(new File("F:\\images\\"+fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.error("文件不存在！"+e.getMessage());
        }
        return ResponseResult.success("文件上传成功！");
    }


    /* 文件下载 */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        // 输入流读取文件内容
        try {
            FileInputStream fileInputStream = new FileInputStream(new File("F:\\images\\"+name));
            //设置写回格式
            response.setContentType("image/jpeg");
            // 输出流将文件写回浏览器
            int len=0;
            byte[] bytes = new byte[1024];
            ServletOutputStream outputStream = response.getOutputStream();
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            // 关闭流
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

